/**
 * Created by Jone on 2016/7/14.
 */
var express = require('express');
var router = express.Router();
var Interface = require('../models/interface_model.js').Interface;
var Group = require('../models/group_model.js').Group;

/* GET home page. */
router.post('/', function (req, res) {
    console.log('请求参数：' + JSON.stringify(req.body));
    Interface.create(req.body, function(err, interface){
        if (err) {
            console.log('保存失败');
        } else {
            var result = {code: 0, msg: '保存成功！', data : interface};
            res.json(result);
        }
    });
});

router.put('/', function (req, res) {
    console.log('请求参数：' + JSON.stringify(req.body));
    Interface.findByIdAndUpdate(req.body._id, {$set : req.body}, function(err){
        if(err) {
            console.log('更新失败');
        } else {
            console.log('更新成功');
            var result = {code: 0, msg: '更新成功！',data : req.body};
            res.json(result);
        };
    });
});

router.get('/', function (req, res) {
    Interface.find({}).populate('groupId').exec(function (err, docs) {
        console.log('query result:' + JSON.stringify(docs));
        var groups = [];
        docs.forEach(function(doc){
            var group = doc.groupId;
            //如果不存在该对象
            group.interfaces = [];
            if(groups.indexOf(group) == -1) {
                groups.push(group);
            }
            console.log('group:' + JSON.stringify(group));
        });
        console.log('groups:' + JSON.stringify(groups));
        console.log('docs:' + JSON.stringify(docs));

        groups.forEach(function(group){
            docs.forEach(function(doc){
                if(group._id == doc.groupId._id) {
                    group.interfaces.push(doc);
                }
            });
        });
        res.json({code: 0, msg: 'success', data: groups});
        console.log('response:' + JSON.stringify(groups));
    });
});

router.delete('/:id', function (req, res) {
    var query = Interface.remove({"_id" : req.params.id}, function (err, docs) {
        console.log('delete info:' + JSON.stringify(docs));
        res.json({code: 0, msg: 'success', data: docs});
    });
});


module.exports = router;